<?php
class Search_test extends CI_Controller
{
	function __construct()
	{
		parent::__construct();
		$this->load->model('Test_model');
		// load the database and connect to MySQL
		$this->load->database();
	}

	function index()
	{
		// 		$this->create_index();
		$data['perguntas'] = $this->search();
		$this->load->view('search_test_view',$data);
	}

	function sanitize($input)
	{
		return htmlentities(strip_tags($input));
	}
	function create_index(){
		// 		$this->load->library('zend', 'Zend/Feed');
		$this->load->library('zend', 'Zend/Search/Lucene');
		$this->load->library('zend');
		// 		$this->zend->load('Zend/Feed');
		$this->zend->load('Zend/Search/Lucene');

		//Create index.
		$index = new Zend_Search_Lucene('index/perguntas_index', true);
		// 		$feeds = array(
		// 				'http://www.cmjackson.net/feed/rss/',
		// 				'http://andrewmjackson.com/feed/rss');
		$questions = $this->Test_model->find();
		//grab each feed.
		foreach($questions as $question)
		{
			// 			$channel = Zend_Feed::import($feed);
			// 			echo $channel->title().'<br />';

			//index each item.
			// 			foreach($channel->items as $item)
			// 			{
			$encoder = "UTF-8";
			if ($question->id && $question->url && $question->descricao && $question->titulo)
			{
				//create an index doc.
				$doc = new Zend_Search_Lucene_Document();
				$doc->addField(Zend_Search_Lucene_Field::Keyword(
						'titulo', $this->sanitize($question->titulo)),$encoder);
				$doc->addField(Zend_Search_Lucene_Field::Text(
						'url', $this->sanitize($question->url)),$encoder);
				$doc->addField(Zend_Search_Lucene_Field::Unstored(
						'descricao', $this->sanitize($question->descricao)),$encoder);
				$doc->addField(Zend_Search_Lucene_Field::unIndexed(
						'descricao', $this->sanitize($question->descricao)),$encoder);

				echo "\tAdding: ". $question->id .'<br />';
				$index->addDocument($doc);
			}
		}
		// 		}

		$index->commit();
		echo $index->count() .' Documents indexed.<br />';
	}
	function search()
	{
		$this->load->library('zend', 'Zend/Search/Lucene');
		$this->load->library('zend');
		$this->zend->load('Zend/Search/Lucene');

		$index = new Zend_Search_Lucene('index/perguntas_index');

		$query = 'a';
		$hits = $index->find($query);

// 		echo 'Index contains '. $index->count() .
// 		' documents.<br /><br />';
// 		echo 'Search for "'. $query .'" returned '. count($hits) .
// 		' hits<br /><br />';

		return $hits;
		// 		foreach($hits as $hit)
			// 		{
			// 			echo 'id: '. $hit->id .'<br />';
			// 			echo 'titulo: '.$hit->titulo .'<br />';
			// 			echo 'url: '.$hit->url .'<br />';
			// 			echo 'descricao: '.$hit->descricao .'<br ><br />';
			// 		}
	}
}